<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\product\Product;
use app\models\Search;
use app\redis\Cache;
use app\util\Agent;
use app\util\Util;

class SearchController extends H5Controller
{
    public function actionSearch()
    {
        $keyword = trim($this->post('keyword'));
        $keyword = substr($keyword, 0, 250);

        $user_id = intval($this->post('user_id', 0));
        $is_wx = $this->post('is_wx', '否');

        // $num = 5;
        $list = Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            ->andWhere(['like', 'title', $keyword])
            ->orderBy(['is_recommend' => SORT_DESC, 'sort' => SORT_ASC, 'id' => SORT_DESC])
            // ->limit($num)
            ->with(['mainImage'])
            ->asArray()
            ->all();

        // save search
        $model = Search::findOne(['keyword' => $keyword]);
        if ($model) {
            $model->total += 1;
            $model->save();
        } else {
            $model = new Search();
            $model->keyword = $keyword;
            $model->user_id = $user_id;
            $model->total = 1;
            $model->ip = Util::getClientIp();
            $model->os = Agent::getOS();
            $model->browser = Agent::getBrowse();
            $model->mobile = Agent::getMobile();
            $model->is_wx = $is_wx;
            $model->result = json_encode($list);
            $model->save();
        }

        return $this->successEncode($list);
    }

    public function actionHot()
    {
        $key = Cache::$SEARCH_HOT;
        $cache = Cache::get($key);
        if (!$cache) {
            $num = 10;

            $list = Product::find()
                ->where(['status' => Product::$statusMapping['OK']])
                ->orderBy(['is_recommend' => SORT_DESC, 'sort' => SORT_ASC, 'id' => SORT_DESC])
                ->limit($num)
                ->with(['mainImage'])
                ->asArray()
                ->all();

            Cache::set($key, json_encode($list));
        } else {
            $list = json_decode($cache, true);
        }

        return $this->successEncode($list);
    }
}